package com.example.androidmainshixun.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.androidmainshixun.R;
import com.example.androidmainshixun.entity.NewsItem;
import com.example.androidmainshixun.view.NewsDetailActivity;

import java.util.List;

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
    private List<NewsItem> newsList;
    public NewsAdapter(List<NewsItem> newsList) {
        this.newsList = newsList;
    }

    @Override
    public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // 正确传递 parent 的上下文
        Context context = parent.getContext(); // 获取正确的上下文
        View view = LayoutInflater.from(context).inflate(R.layout.item_news, parent, false);
        return new NewsViewHolder(view);
    }
    @Override
    public void onBindViewHolder(NewsViewHolder holder, int position) {
        NewsItem newsItem = newsList.get(position);
        holder.titleTextView.setText(newsItem.getTitle());
        holder.firstImageView.setImageResource(newsItem.getImageResourceId());
        holder.dateTextView.setText(newsItem.getPublishDate());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int currentPosition = holder.getAdapterPosition();
                if (currentPosition == 0) {
                    NewsItem clickedNewsItem = newsList.get(currentPosition);
                    Intent intent = new Intent(holder.itemView.getContext(), NewsDetailActivity.class);
                    if (clickedNewsItem.getUrl() != null && !clickedNewsItem.getUrl().isEmpty()) {
                        intent.putExtra("news_url", clickedNewsItem.getUrl());
                        holder.itemView.getContext().startActivity(intent);
                    }
                }
            }
        });
    }
    @Override
    public int getItemCount() {
        return newsList.size();
    }

    public static class NewsViewHolder extends RecyclerView.ViewHolder {
        TextView titleTextView;
        ImageView firstImageView;
        TextView dateTextView;
        @SuppressLint("WrongViewCast")
        public NewsViewHolder(View itemView) {
            super(itemView);
            titleTextView = itemView.findViewById(R.id.news_title);
            firstImageView=itemView.findViewById(R.id.news_image);
            dateTextView=itemView.findViewById(R.id.date);
        }
    }
}
